package com.ruoyi.wechat.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.wechat.component.WeChatTokenService;
import com.ruoyi.wechat.domain.WxUser;
import com.ruoyi.wechat.mapper.WeChatLoginUser;
import com.ruoyi.wechat.service.IWeChatBaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

/**
 * @author cj
 */
@Component
@Slf4j
public class WeChatTokenInterceptor implements HandlerInterceptor {


    @Autowired
    WeChatTokenService weChatTokenService;
    @Autowired
    IWeChatBaseService weChatBaseService;

    /**
     * 白名单
     */
    private final String[] whitelist = {"/pay/notify-order","/base/login","/system/captchaImage","/hello","/base/redirect/auth","/notify","/base/getWebAuthUrl"};


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String requestUrl = request.getRequestURI().split("/wechat")[1];
        if (Arrays.asList(whitelist).contains(requestUrl)){
            return true;
        }
        WeChatLoginUser weChatLoginUser = weChatTokenService.getLoginUser(request);
        if (weChatLoginUser != null){
            request.setAttribute("user",weChatLoginUser);
            weChatTokenService.refreshToken(weChatLoginUser);
            return true;
        }
        if (request.getParameterValues("state")!=null && request.getParameterValues("code")!=null
        &&  request.getParameterValues("code").length>0
        ){
           String code =  request.getParameterValues("code")[0];
            JSONObject authObj = weChatBaseService.webLogin(code);
            WxUser wxUser = weChatBaseService.getAndAddUserByOpenid(authObj.getString("openid"));
            weChatLoginUser =  new WeChatLoginUser(wxUser,null);
           String   token = weChatTokenService.createToken(weChatLoginUser);
            log.debug("产生新的token，是:{}",token);
            response.addHeader("token",token );
            response.addHeader("Access-Control-Expose-Headers","token");
            request.setAttribute("user",weChatLoginUser);
            return true;
        }

        //认证失败
        int code = HttpStatus.UNAUTHORIZED;
        String msg = StringUtils.format("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
        //返回 false 则请求中断
        return false;
    }

}
